package com.study.base.io.nio.mainsubreactor;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by tan on 2017/7/18.
 */
public class SubReactor implements Runnable {
	private Selector selector;
	private ServerSocketChannel serverSocket;
	private boolean restart = false;
	private int num; //编号

	public SubReactor(Selector selector, ServerSocketChannel serverSocket, int num) {
		this.selector = selector;
		this.serverSocket = serverSocket;
		this.num = num;
	}

	@Override
	public void run() {
		while (!Thread.interrupted()) {

			while (!Thread.interrupted() && !restart) {
				try {
					Set<SelectionKey> keySet = selector.selectedKeys();
					Iterator it = keySet.iterator();
					while (it.hasNext()) {
						//当key.isAcceptable()==true时，key是serverSocket的key
						//当key.isReadable()==true时，key是客户端的key
						dispatch((SelectionKey) it.next());
					}

					keySet.clear();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	private void dispatch(SelectionKey key) {
		Runnable r = (Runnable) (key.attachment());
		if (r != null)
			r.run();
	}

	public void setRestart(boolean restart) {
		this.restart = restart;
	}
}
